package com.serviceprovider.business.module.exception;

//~--- non-JDK imports --------------------------------------------------------

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

//~--- JDK imports ------------------------------------------------------------

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@Service("emailNotificationService")
public class EmailNotificationServiceImpl implements NotificationService {
    public static final Logger logger = Logger.getLogger(EmailNotificationServiceImpl.class);
    @Autowired
    private MailSender         mailSender;
    @Autowired
    private SimpleMailMessage  templateMessage;

    public void sendNotification(String message, Exception exception) {
        SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
        StringBuffer      buf = new StringBuffer("Application Message - " + message + " : "
                               + exception.getMessage()).append("\n");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintStream           writer       = new PrintStream(outputStream);

        exception.printStackTrace(writer);
        buf.append(new String(outputStream.toByteArray()));
        msg.setText(buf.toString());

        try {
            this.mailSender.send(msg);
        } catch (MailException ex) {
            logger.error("Email Notification message could not sent", ex);
        }
    }

    @Override
    public void sendNotification(String email, String message, String userRecoverPasswordNotificationMessageTitle) {
        SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);

        msg.setTo(new String[] { email });
        msg.setSubject(userRecoverPasswordNotificationMessageTitle);

        StringBuilder buf = new StringBuilder(message).append("\n");

        msg.setText(buf.toString());

        try {
            mailSender.send(msg);
        } catch (MailException ex) {
            logger.error("Email Notification message could not sent", ex);
        }
    }
}



